<template>
  <div class="schools-page">
    <div class="page-header">
      <h1 class="page-title">校园二手交易</h1>
      <p class="page-description">选择您所在的学校，浏览校内二手商品和活动</p>
      
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索学校"
          clearable
          :prefix-icon="Search"
          class="search-input"
          @update:model-value="filterSchools"
        />
        
        <el-select
          v-model="selectedProvince"
          placeholder="省份筛选"
          clearable
          class="region-select"
          @change="filterSchools"
        >
          <el-option
            v-for="province in provinces"
            :key="province"
            :label="province"
            :value="province"
          />
        </el-select>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else>
      <div v-if="filteredSchools.length === 0" class="empty-results">
        <el-empty description="未找到学校" :image-size="200">
          <template #description>
            <p>没有符合条件的学校</p>
            <p class="empty-suggestion">尝试使用其他关键词搜索</p>
          </template>
        </el-empty>
      </div>
      
      <div v-else>
        <div class="featured-schools" v-if="featuredSchools.length > 0">
          <h2 class="section-title">推荐学校</h2>
          <div class="featured-grid">
            <el-card 
              v-for="school in featuredSchools" 
              :key="school.id" 
              class="featured-school-card"
              shadow="hover"
              @click="goToSchool(school.id)"
            >
              <div class="featured-card-content">
                <div class="featured-school-image">
                  <el-image :src="school.image" fit="cover" />
                </div>
                <div class="featured-school-info">
                  <h3 class="featured-school-name">{{ school.name }}</h3>
                  <div class="featured-school-meta">
                    <span class="featured-meta-item">
                      <el-icon><ShoppingCart /></el-icon>
                      {{ school.productCount }}件商品
                    </span>
                    <span class="featured-meta-item">
                      <el-icon><User /></el-icon>
                      {{ school.memberCount }}位成员
                    </span>
                  </div>
                  <p class="featured-school-description">{{ school.description }}</p>
                  <div class="featured-school-tags">
                    <el-tag 
                      v-for="tag in school.tags" 
                      :key="tag"
                      size="small"
                      effect="plain"
                      class="school-tag"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
        
        <h2 class="section-title">全部学校</h2>
        <div class="region-list">
          <div 
            v-for="(schools, province) in groupedSchools" 
            :key="province"
            class="region-group"
          >
            <h3 class="region-title" :id="'province-' + province">{{ province }}</h3>
            <div class="schools-gallery">
              <div 
                v-for="school in schools" 
                :key="school.id" 
                class="school-gallery-item"
                @click="goToSchool(school.id)"
              >
                <div class="school-gallery-image">
                  <el-avatar :size="160" :src="school.logoUrl || school.logo" fit="cover" class="school-logo" />
                </div>
                <div class="school-gallery-content">
                  <h4 class="school-gallery-name">{{ school.name }}</h4>
                  <p class="school-gallery-count">{{ school.productCount }}件商品</p>
                  <el-progress :percentage="getSchoolPercentage(school)" :color="getSchoolColor(school)" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { School, Search, ShoppingCart, User } from '@element-plus/icons-vue';
import { getSchools } from '@/api/school';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 处理学校logo路径的函数
const getLogoUrl = (filename) => {
  if (!filename) return '';
  // 如果已经是完整的URL，则直接返回
  if (filename.startsWith('http')) return filename;
  
  try {
    // 尝试使用动态导入
    return new URL(`../../assets/images/${filename}`, import.meta.url).href;
  } catch (error) {
    console.error('加载logo图片失败:', error, filename);
    return '';
  }
};

// 页面状态
const searchKeyword = ref('');
const selectedProvince = ref('');
const loading = ref(true);

// 学校数据
const schools = ref([]);
const filteredSchools = ref([]);

// 从学校数据中提取所有省份
const provinces = computed(() => {
  const provinceSet = new Set();
  
  schools.value.forEach(school => {
    const province = school.province || school.city || '未知省份';
    provinceSet.add(province);
  });
  
  return Array.from(provinceSet).sort();
});

// 获取推荐学校
const featuredSchools = computed(() => {
  return filteredSchools.value.filter(school => school.featured).slice(0, 6);
});

// 按省份分组学校
const groupedSchools = computed(() => {
  const grouped = {};
  
  filteredSchools.value.forEach(school => {
    // 使用province作为分组键，如果不存在则使用city作为备选
    const province = school.province || school.city || '未知省份';
    if (!grouped[province]) {
      grouped[province] = [];
    }
    grouped[province].push(school);
  });
  
  // 按字母顺序排序省份
  return Object.keys(grouped)
    .sort()
    .reduce((acc, province) => {
      acc[province] = grouped[province].sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
      return acc;
    }, {});
});

// 加载学校数据
const loadSchools = async () => {
  loading.value = true;
  
  try {
    // 从后端API获取学校列表
    const response = await getSchools();
    if (response.code === 200 && response.data) {
      // 确保数据中包含必要的字段
      const apiSchools = response.data.map(school => ({
        ...school,
        logo: school.logo || '',
        logoUrl: getLogoUrl(school.logo),  // 添加处理后的logo URL
        image: school.cover || '/src/assets/school-placeholder.png',
        province: school.province || school.city || '未知省份', // 确保有省份字段
        productCount: school.productCount || 0,
        memberCount: school.memberCount || 0,
        tags: school.tags || [],
        // 初始化featured为false，后面会重新设置
        featured: false
      }));
      
      // 按商品数量排序并将前六个标记为推荐学校
      apiSchools.sort((a, b) => b.productCount - a.productCount);
      for (let i = 0; i < Math.min(6, apiSchools.length); i++) {
        apiSchools[i].featured = true;
      }
      
      schools.value = apiSchools;
      filteredSchools.value = apiSchools;
      console.log('成功从后端获取学校列表:', apiSchools.length);
    } else {
      // API返回异常，使用模拟数据
      console.warn('API返回数据异常，使用模拟数据');
      useDefaultSchools();
      ElMessage.warning('获取学校列表失败，使用默认数据');
    }
  } catch (error) {
    console.error('加载学校数据出错:', error);
    // 发生错误时使用模拟数据
    useDefaultSchools();
    ElMessage.warning('获取学校列表失败，使用默认数据');
  } finally {
    loading.value = false;
  }
};

// 使用默认模拟数据
const useDefaultSchools = () => {
  const mockSchools = [
    {
      id: 1,
      name: '北京大学',
      logo: '北大.png',
      logoUrl: getLogoUrl('北大.png'),
      image: '/src/assets/school-placeholder.png',
      region: '华北',
      province: '北京',
      city: '北京',
      description: '北京大学是中国最著名的综合研究型大学，拥有丰富的校园二手交易资源。',
      productCount: 1245,
      memberCount: 3500,
      tags: ['985工程', '211工程', '双一流'],
      featured: true
    },
    {
      id: 2,
      name: '清华大学',
      logo: '清华.png',
      logoUrl: getLogoUrl('清华.png'),
      image: '/src/assets/school-placeholder.png',
      region: '华北',
      province: '北京',
      city: '北京',
      description: '清华大学是中国顶尖的理工类大学，校园二手交易平台活跃。',
      productCount: 1560,
      memberCount: 4200,
      tags: ['985工程', '211工程', '双一流'],
      featured: true
    },
    {
      id: 3,
      name: '复旦大学',
      logo: 'fudan.png',
      logoUrl: getLogoUrl('fudan.png'),
      image: '/src/assets/school-placeholder.png',
      region: '华东',
      province: '上海',
      city: '上海',
      description: '复旦大学是华东地区顶尖的综合型研究大学，二手交易品类丰富。',
      productCount: 980,
      memberCount: 2800,
      tags: ['985工程', '211工程', '双一流'],
      featured: true
    },
    {
      id: 4,
      name: '浙江大学',
      logo: 'zheda.png',
      logoUrl: getLogoUrl('zheda.png'),
      image: '/src/assets/school-placeholder.png',
      region: '华东',
      province: '浙江',
      city: '杭州',
      description: '浙江大学是中国综合性大学中的佼佼者，二手交易社区活跃。',
      productCount: 1020,
      memberCount: 3100,
      tags: ['985工程', '211工程', '双一流'],
      featured: false
    },
    {
      id: 5,
      name: '南京大学',
      logo: 'nanda.png',
      logoUrl: getLogoUrl('nanda.png'),
      image: '/src/assets/school-placeholder.png',
      region: '华东',
      province: '江苏',
      city: '南京',
      description: '南京大学是华东地区著名的综合研究型大学，校内二手交易平台发展良好。',
      productCount: 870,
      memberCount: 2500,
      tags: ['985工程', '211工程', '双一流'],
      featured: false
    },
    {
      id: 6,
      name: '中山大学',
      logo: '',
      image: '/src/assets/school-placeholder.png',
      region: '华南',
      province: '广东',
      city: '广州',
      description: '中山大学是华南地区重点大学，二手交易市场繁荣。',
      productCount: 790,
      memberCount: 2300,
      tags: ['985工程', '211工程', '双一流'],
      featured: false
    },
    {
      id: 7,
      name: '武汉大学',
      logo: 'wuda.png',
      logoUrl: getLogoUrl('wuda.png'),
      image: '/src/assets/school-placeholder.png',
      region: '华中',
      province: '湖北',
      city: '武汉',
      description: '武汉大学是中部地区知名高校，校园二手交易平台用户活跃。',
      productCount: 850,
      memberCount: 2600,
      tags: ['985工程', '211工程', '双一流'],
      featured: false
    },
    {
      id: 8,
      name: '四川大学',
      logo: '',
      image: '/src/assets/school-placeholder.png',
      region: '西南',
      province: '四川',
      city: '成都',
      description: '四川大学是西南地区重点综合性大学，拥有活跃的校内二手交易社区。',
      productCount: 720,
      memberCount: 2200,
      tags: ['985工程', '211工程', '双一流'],
      featured: false
    },
    {
      id: 9,
      name: '西安交通大学',
      logo: '',
      image: '/src/assets/school-placeholder.png',
      region: '西北',
      province: '陕西',
      city: '西安',
      description: '西安交通大学是西北地区著名的理工科大学，校内二手交易平台资源丰富。',
      productCount: 680,
      memberCount: 2000,
      tags: ['985工程', '211工程', '双一流'],
      featured: false
    },
    {
      id: 10,
      name: '哈尔滨工业大学',
      logo: '',
      image: '/src/assets/school-placeholder.png',
      region: '东北',
      province: '黑龙江',
      city: '哈尔滨',
      description: '哈尔滨工业大学是东北地区知名的理工科大学，二手交易主要以电子产品为主。',
      productCount: 650,
      memberCount: 1900,
      tags: ['985工程', '211工程', '双一流'],
      featured: false
    },
    {
      id: 11,
      name: '中国人民大学',
      logo: '',
      image: '/src/assets/school-placeholder.png',
      region: '华北',
      province: '北京',
      city: '北京',
      description: '中国人民大学是以人文社会科学为主的综合性研究型大学，二手图书交易活跃。',
      productCount: 780,
      memberCount: 2100,
      tags: ['985工程', '211工程', '双一流'],
      featured: false
    },
    {
      id: 12,
      name: '上海交通大学',
      logo: 'shangjiaoda.png',
      logoUrl: getLogoUrl('shangjiaoda.png'),
      image: '/src/assets/school-placeholder.png',
      region: '华东',
      province: '上海',
      city: '上海',
      description: '上海交通大学是中国历史悠久的高等学府，校园二手交易平台品类齐全。',
      productCount: 930,
      memberCount: 2700,
      tags: ['985工程', '211工程', '双一流'],
      featured: false
    }
  ];
  
  schools.value = mockSchools;
  filteredSchools.value = mockSchools;
};

// 筛选学校
const filterSchools = () => {
  try {
    const keyword = searchKeyword.value ? searchKeyword.value.toLowerCase().trim() : '';
    const province = selectedProvince.value;
    
    console.log('筛选条件:', { keyword, province });
    
    // 确保schools.value是一个数组
    if (!Array.isArray(schools.value)) {
      console.error('schools.value不是数组:', schools.value);
      filteredSchools.value = [];
      return;
    }
    
    filteredSchools.value = schools.value.filter(school => {
      // 确保学校对象有效
      if (!school) return false;
      
      const matchKeyword = !keyword || 
        (school.name && school.name.toLowerCase().includes(keyword)) || 
        (school.description && typeof school.description === 'string' && school.description.toLowerCase().includes(keyword)) || 
        (school.city && school.city.toLowerCase().includes(keyword));
        
      const matchProvince = !province || 
        (school.province && school.province === province) || 
        (school.city && school.city === province);
      
      return matchKeyword && matchProvince;
    });
    
    console.log('筛选结果数量:', filteredSchools.value.length);
  } catch (error) {
    console.error('筛选学校时发生错误:', error);
    ElMessage.error('筛选学校失败');
  }
};

// 跳转到学校详情
const goToSchool = (schoolId) => {
  router.push(`/school/${schoolId}`);
};

// 计算学校百分比（用于进度条）
const getSchoolPercentage = (school) => {
  // 查找最大商品数量
  const maxCount = Math.max(...schools.value.map(s => s.productCount || 0));
  return maxCount > 0 ? Math.round((school.productCount / maxCount) * 100) : 0;
};

// 获取学校颜色
const getSchoolColor = (school) => {
  const colors = ['#f56c6c', '#e6a23c', '#409eff', '#67c23a', '#909399'];
  return colors[school.id % colors.length];
};

// 初始化数据和事件
onMounted(() => {
  loadSchools();
});
</script>

<style scoped>
.schools-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
  background-color: #f5f5f7;
}

.page-header {
  text-align: center;
  margin-bottom: 48px;
  animation: fadeIn 0.8s ease-out;
}

.page-title {
  font-size: 40px;
  font-weight: 700;
  color: #1d1d1f;
  margin-bottom: 12px;
  letter-spacing: -0.5px;
}

.page-description {
  font-size: 20px;
  color: #86868b;
  margin-bottom: 32px;
  line-height: 1.4;
}

.search-container {
  display: flex;
  gap: 16px;
  max-width: 800px;
  margin: 0 auto;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 12px;
  height: 48px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.region-select {
  width: 160px;
}

.region-select :deep(.el-input__wrapper) {
  border-radius: 12px;
  height: 48px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.region-select :deep(.el-input__wrapper):hover {
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.featured-schools {
  margin-bottom: 48px;
}

.section-title {
  font-size: 28px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 24px;
  letter-spacing: -0.3px;
}

.featured-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  margin-bottom: 40px;
  justify-content: flex-start;
}

.featured-school-card {
  border-radius: 16px;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  width: 380px;
  flex-grow: 0;
}

.featured-school-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.featured-school-image {
  height: 200px;
  overflow: hidden;
}

.featured-school-image :deep(img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.featured-school-card:hover .featured-school-image :deep(img) {
  transform: scale(1.05);
}

.featured-school-info {
  padding: 20px;
}

.featured-school-name {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.featured-school-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
  color: #86868b;
}

.featured-meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.featured-school-description {
  color: #424245;
  font-size: 15px;
  line-height: 1.4;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.school-tag {
  margin-right: 8px;
  margin-bottom: 8px;
  border-radius: 6px;
}

.schools-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 35px;
  margin-bottom: 32px;
}

.school-gallery-item {
  background: white;
  border-radius: 20px;
  padding: 35px 25px;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.03);
  position: relative;
  overflow: hidden;
}

.school-gallery-item:hover {
  transform: translateY(-15px);
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
}

.school-gallery-image {
  margin-bottom: 25px;
  position: relative;
}

.school-logo {
  border: 8px solid white;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
  transition: transform 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.school-gallery-item:hover .school-logo {
  transform: scale(1.15);
}

.school-gallery-content {
  width: 100%;
  text-align: center;
}

.school-gallery-name {
  margin: 0 0 12px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.school-gallery-count {
  margin: 0 0 20px;
  font-size: 15px;
  color: #666;
}

.school-gallery-item .el-progress {
  margin-top: 5px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
  }
  
  .region-select {
    width: 100%;
  }
  
  .featured-grid {
    grid-template-columns: 1fr;
  }
  
  .schools-gallery {
    grid-template-columns: 1fr;
  }
  
  .page-title {
    font-size: 32px;
  }
  
  .page-description {
    font-size: 18px;
  }
}
</style> 